package com.jingfu.heefss.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2019/12/25 14:18
 * @description 博罗县房管通讯加密工具类，AES+BASE64
 **/
public class AESUtils {
    /**
     * 加密时使用的key，16位字符串
     */
    private    String salKey;

    /**
     * 加密时使用的向量，16位字符串
     */
    private   String vectorkey;

    public AESUtils() {
    }

    public AESUtils(String salKey, String vectorkey) {
        this.salKey = salKey;
        this.vectorkey = vectorkey;
    }

    public String getSalKey() {
        return salKey;
    }

    public void setSalKey(String salKey) {
        this.salKey = salKey;
    }

    public String getVectorkey() {
        return vectorkey;
    }

    public void setVectorkey(String vectorkey) {
        this.vectorkey = vectorkey;
    }

    public String encrypt(String content) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(getSalKey().getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(getVectorkey().getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return Base64.encodeBase64String(encrypted);
    }

    public  String decrypt(String base64Content) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(getSalKey().getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(getVectorkey().getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] content = Base64.decodeBase64(base64Content);
        byte[] encrypted = cipher.doFinal(content);
        return new String(encrypted);
    }

    public static void main(String[] args) {
        String key = "2018010120181231";
        String vector = "1122334455667788";
        String result = "So1QhLgJUPwTgAS27d3d3C5Co5hp0NVncPDsmlQV76P/3SKqhbTG/QTVm5FVLAg1L/1/A\n" +
                "q8cpsCA \n" +
                "PbNy0vXX9w== \n" +
                "So1QhLgJUPwTgAS27d3d3C5Co5hp0NVncPDsmlQV76P/3SKqhbTG/QTVm5FVLAg1L/1/A\n" +
                "q8cpsCA \n" +
                "PbNy0vXX9w==";
        AESUtils aesUtils = new AESUtils(key, vector);
        String decrypt = null;
        try {
            decrypt = aesUtils.decrypt(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(decrypt);
    }
}
